var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var ConnectionPool = require('tedious-connection-pool');

var poolConfig = {
    min: 2,
    max: 10,
    log: false
};


var pool = null;
var connection = null;

var connectionConfig = require('./config/msdbconfig');
pool = new ConnectionPool(poolConfig, connectionConfig);
pool.on('error', function(err) {
	console.error("pool error", err);
});

/*
* 执行sql语句
* fun 语句执行完执行的函数 参数返回rows
* param 传个sql的参数
*/
function executeSql(sql, fun, param, retArray)
{
	//console.log('executeSql: ', sql);
	pool.acquire(function (err, connection) {
		if (err) 
		{
			LOG.error(err);
			if(connection) connection.release();
			if(fun) setTimeout(()=>{fun(retArray?[]:{},err);},0);
			return;
		}

		var req = new Request(sql, function(err, rowCount, rows) {
			var rdata = retArray?[]:{};
			if(connection) connection.release();
			if (err)
			{
				if(fun) setTimeout(()=>{fun(rdata,err);},0);
				LOG.error("pool req", sql, err);
				for(var id in param)
				{
					LOG.error("pool req", param[id].name, param[id].value);
				}
				return;
			}					
			
			if(rows && rows.length > 0)
			{
				if(retArray){
					rdata = [];
					for(let i=0;i<rows.length;i++){
						let row = {};
						for(let j=0;j<rows[i].length;j++){
							row[rows[i][j].metadata.colName] = rows[i][j].value;
						}
						rdata.push(row);
					}
				}else{
					for(var i=0;i<rows.length;i++){
						for(var j=0;j<rows[i].length;j++){
							if(!(rows[i][j].metadata.colName in rdata)) 
								rdata[rows[i][j].metadata.colName]= [];
							rdata[rows[i][j].metadata.colName][i] = rows[i][j].value;
						}
					}
				}
			}
			if(fun) setTimeout(()=>{fun(rdata,null);},0);
		});
		
		if(param)
		{
			for(var id in param)
			{
				req.addParameter(param[id].name, param[id].type, param[id].value, (param[id].options||null));
			}
		}

		connection.execSql(req);
	});
}

exports.executeSql = executeSql;
exports.TYPES = require('tedious').TYPES;



